package com.grapefruitchat;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.grapefruitchat.client.net.NetworkCommsDelegate;

/**
 * Command line version of Grapefruit Chat.
 * 
 * @author Michael Gierasimiuk, Innovation Science Pty Ltd.
 */
public class CommandLineMain
{
  private String DEFAULT_USERNAME = "Default User";
  private String username = DEFAULT_USERNAME;
  
  private NetworkCommsDelegate network;
  
  /**
   * Creates a new {@link CommandLineMain}.
   * 
   * @param aUsername the username, as a string. If no valid username is passed
   *          through, the application will use a default username.
   */
  public CommandLineMain( String aUsername )
  {
    if ( aUsername != null && aUsername.isEmpty() == false )
    {
      username = aUsername;
    }
    network = new NetworkCommsDelegate( username );
    network.connect();
    loop();
    network.disconnect();
  }
  
  private void loop()
  {
    BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
    System.out.print( ">> " );
    while ( true )
    {
      try
      {
        System.out.flush();
        
        String line = in.readLine();
        String lineLowerCase = line.toLowerCase();
        
        if ( isCommand( lineLowerCase ) )
        {
          if ( isQuitCommand( lineLowerCase ) )
          {
            break;
          }
        }
        
        // Send the original line with casing
        network.send( line );
      }
      catch ( Exception exception )
      {
        // TODO LOGGING
        exception.printStackTrace();
      }
    }
  }

  private boolean isCommand( String aInput )
  {
    // Allow the user to use any of the following escape characters to enter
    // command mode.
    if ( aInput.startsWith( "\\" ) )
    {
      return true;
    }
    if ( aInput.startsWith( ":" ) )
    {
      return true;
    }
    if ( aInput.startsWith( "/" ) )
    {
      return true;
    }
    return false;
  }
  
  private boolean isQuitCommand( String aInput )
  {
    if ( aInput.contains( "exit" ) )
    {
      return true;
    }
    if ( aInput.contains( "quit" ) )
    {
      return true;
    }
    if ( aInput.contains( "q" ) )
    {
      return true;
    }
    return false;
  }
  
  /**
   * The main method for the application.
   * 
   * @param args command line arguments.
   */
  public static final void main( String... args )
  {
    if ( args.length > 0 )
    {
      new CommandLineMain( args[0] );
    }
    else
      {
      new CommandLineMain( null );
    }
  }
}
